package com.yb.bluetooth.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.yb.bluetooth.R
import com.yb.bluetooth.entity.BtItem

/**
 * Created by zyb
 * Date 2022/2/8 17:14
 * Desc
 */

class BtDeviceListAdapter : BaseAdapter() {

    var data: MutableList<BtItem> = arrayListOf()

    override fun getCount(): Int {
        return data.size
    }

    override fun getItem(position: Int): BtItem {
        return data[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val holder: ViewHolder
        var itemView: View? = convertView
        if (itemView == null) {
            itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_device, parent, false)
            holder = ViewHolder(itemView)
            itemView.tag = holder
        } else {
            holder = itemView.tag as ViewHolder
        }
        onBindItem(holder, getItem(position))
        return holder.itemView
    }

    @SuppressLint("SetTextI18n")
    private fun onBindItem(holder: ViewHolder, item: BtItem) {
        holder.tvName.text = "蓝牙名称：${item.deviceName}"
        holder.tvMac.text = "mac地址：${item.deviceAddress}"
    }

     fun setList(list: Collection<BtItem>) {
         this.data.clear()
         this.data.addAll(list)
        notifyDataSetChanged()
    }

    fun addData(btItem: BtItem) {
        this.data.add(btItem)
        notifyDataSetChanged()
    }

    fun remove(item: BtItem) {
        this.data.remove(item)
        notifyDataSetChanged()
    }

    class ViewHolder(val itemView: View) {

        val tvName: TextView = itemView.findViewById(R.id.tv_name)

        val tvMac: TextView = itemView.findViewById(R.id.tv_mac)
    }
}